package com.coffee.admin.service.supplier.impl;

import java.util.Date;

import com.coffee.admin.api.supplier.query.SupplierRolePermissionQuery;
import com.coffee.admin.api.supplier.query.SupplierRoleQuery;
import com.coffee.admin.api.supplier.query.SupplierRoleRelationQuery;
import com.coffee.admin.api.supplier.req.SupplierRoleReq;
import com.coffee.admin.api.supplier.result.SupplierRoleResult;
import com.coffee.admin.api.supplier.service.SupplierRoleService;
import com.coffee.admin.service.platform.bean.PlatformRole;
import com.coffee.admin.service.platform.bean.PlatformRolePermission;
import com.coffee.admin.service.supplier.bean.SupplierRole;
import com.coffee.admin.service.supplier.bean.SupplierRolePermission;
import com.coffee.admin.service.supplier.dao.SupplierRoleDao;
import com.coffee.admin.service.supplier.dao.SupplierRolePermissionDao;
import com.coffee.admin.service.supplier.dao.SupplierRoleRelationDao;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.util.BeanUtilExt;
import com.coffee.core.util.DTOUtils;
import com.coffee.core.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@DubboService(dynamic = true)
public class SupplierRoleServiceImpl implements SupplierRoleService {
    @Resource
    private SupplierRoleDao supplierRoleDao;
    @Resource
    private SupplierRolePermissionDao supplierRolePermissionDao;
    @Resource
    private SupplierRoleRelationDao supplierRoleRelationDao;

    @Override
    public Page<SupplierRoleResult> getPager(SupplierRoleQuery param, PagerInfo pr) {
        Page<SupplierRoleResult> pager = new Page<SupplierRoleResult>(pr.getStart(), pr.getPageSize());
        Integer count = supplierRoleDao.count(param);
        pager.setTotalPage(count);
        if (count > 0) {
            List<SupplierRole> list = supplierRoleDao.page(param, pr.getStart(), pr.getPageSize());
            List<SupplierRoleResult> supplierRoleResults = DTOUtils.convertList(list, SupplierRoleResult.class);
            supplierRoleResults.forEach(role -> {
                SupplierRoleRelationQuery supplierRoleRelationQuery = new SupplierRoleRelationQuery();
                supplierRoleRelationQuery.setSupplierRoleId(role.getId());
                Integer number = supplierRoleRelationDao.count(supplierRoleRelationQuery);
                role.setCount(number);
                //获取权限
                SupplierRolePermissionQuery query = new SupplierRolePermissionQuery();
                query.setSupplierRoleId(role.getId());
                List<SupplierRolePermission> supplierRolePermissions = supplierRolePermissionDao.list(query);
                if (CollectionUtils.isNotEmpty(supplierRolePermissions)) {
                    List<Integer> permissionList = supplierRolePermissions.stream().map(rl -> rl.getSupplierPermissionId()).collect(Collectors.toList());
                    role.setPermissionIds(permissionList.toArray(new Integer[]{}));
                }
            });
            pager.setData(supplierRoleResults);

        }
        return pager;
    }

    @Override
    public Integer count(SupplierRoleQuery param) {
        Integer count = supplierRoleDao.count(param);
        return count;
    }

    @Override
    public SupplierRoleResult getDetail(Integer id, Integer supplierId) {
        SupplierRole item = supplierRoleDao.findById(id);
        if (item == null || item.getSupplierId() != supplierId) {
            return null;
        }
        SupplierRoleResult result = new SupplierRoleResult();
        BeanUtilExt.copyProperties(result, item);
        return result;
    }

    @Override
    public List<SupplierRoleResult> getList(SupplierRoleQuery param, PagerInfo pr) {
        List<SupplierRole> list = supplierRoleDao.page(param, pr.getStart(), pr.getPageSize());
        return DTOUtils.convertList(list, SupplierRoleResult.class);
    }

    @Override
    public List<SupplierRoleResult> getList(SupplierRoleQuery param) {
        List<SupplierRole> list = supplierRoleDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, SupplierRoleResult.class);
    }

    @Override
    public List<SupplierRoleResult> getList() {
        SupplierRoleQuery param = new SupplierRoleQuery();
        List<SupplierRole> list = supplierRoleDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, SupplierRoleResult.class);
    }


    @Override
    public void delete(Integer id, Integer supplierId) {
        supplierRoleDao.deleteById(id, supplierId);
    }

    @Override
    public void addOrUpdate(SupplierRoleReq result) throws BusinessException {
        String roleName = result.getName();
        ValidateBusinessException.assertStringNotBlank(roleName, ExceptionEnum.ERROR_1502);

        Integer[] permissionIds = result.getPermissionIds();
        ValidateBusinessException.assertTrue(result.getPermissionIds().length > 0, ExceptionEnum.ERROR_1503);

        Integer roleId = result.getId();
        if (roleId != null && roleId > 0) {
            SupplierRole supplierRole = supplierRoleDao.findById(roleId);
            ValidateBusinessException.assertTrue("Y".equals(supplierRole.getCanDelete()), ExceptionEnum.ERROR_1504);
            ValidateBusinessException.assertTrue(supplierRole.getSupplierId().equals(result.getSupplierId()), ExceptionEnum.ERROR_1505);
            supplierRole.setName(roleName);
            supplierRoleDao.updateById(supplierRole);
            batchUpdateRolePermission(supplierRole.getId(), new ArrayList<>(Arrays.asList(permissionIds)));
        } else {
            SupplierRole role = new SupplierRole();
            role.setCreateTime(new Date());
            role.setCanDelete("Y");
            role.setName(result.getName());
            role.setSupplierId(result.getSupplierId());
            supplierRoleDao.insert(role);
            batchUpdateRolePermission(role.getId(), new ArrayList<>(Arrays.asList(permissionIds)));
        }
    }

    public void batchUpdateRolePermission(Integer roleId, List<Integer> permissionIdList) {
        supplierRolePermissionDao.deleteBySupplierRoleId(roleId);
        for (Integer permissionId : permissionIdList) {
            SupplierRolePermission rl = new SupplierRolePermission();
            rl.setSupplierRoleId(roleId);
            rl.setSupplierPermissionId(permissionId);
            rl.setCreateTime(new Date());
            supplierRolePermissionDao.insert(rl);
        }
    }

    @Override
    public Map<Integer, SupplierRoleResult> getItemMap(Set<Integer> idSet) {
        Map<Integer, SupplierRoleResult> map = new HashMap<Integer, SupplierRoleResult>();
        List<SupplierRole> list = supplierRoleDao.findByIds(StringUtil.setToList(idSet));
        List<SupplierRoleResult> resultList = DTOUtils.convertList(list, SupplierRoleResult.class);
        for (SupplierRoleResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    @Override
    public Map<Integer, SupplierRoleResult> getItemMap() {
        Map<Integer, SupplierRoleResult> map = new HashMap<Integer, SupplierRoleResult>();
        SupplierRoleQuery param = new SupplierRoleQuery();
        List<SupplierRole> list = supplierRoleDao.page(param, 0, Integer.MAX_VALUE);
        List<SupplierRoleResult> resultList = DTOUtils.convertList(list, SupplierRoleResult.class);
        for (SupplierRoleResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }


}
